﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Project.EPMAuditing.Library;
using System.Reflection;
using System.ServiceProcess;
using System.Globalization;

namespace Microsoft.Office.Project.EPMAuditing.ReceiverService.Monitor
{
    public partial class FormEditListeners : Form
    {
        private EPMAuditingConfigFile _configFile;
        private bool _dirty = false;
        private string _epmAuditServiceName;

        public FormEditListeners(string epmAuditServiceName)
        {
            InitializeComponent();
            _epmAuditServiceName = epmAuditServiceName;
        }

        #region Event Handlers

        private void FormEditListeners_Load(object sender, EventArgs e)
        {
            // Read configuration file
            string fullPath = Assembly.GetExecutingAssembly().Location;
            _configFile = new EPMAuditingConfigFile(string.Format(CultureInfo.InvariantCulture, "{0}{1}", 
                fullPath.Substring(0, fullPath.LastIndexOf(@"\", StringComparison.OrdinalIgnoreCase) + 1),
                EPMAuditingConfigFile.DEFAULT_CONFIG_FILENAME));

            foreach (Listener item in _configFile.AuditingConfiguration.Listeners)
            {
                dataGridViewListeners.Rows.Add(ListenerRow(item.Enabled, item.ClassName));
            }
            _dirty = false;
        }

        private void dataGridViewListeners_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            _dirty = true;
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            if (_dirty)
            {
                WriteChanges();
            }
        }

        #endregion

        private static DataGridViewRow ListenerRow(bool enabled, string className)
        {
            DataGridViewRow listenerRow = new DataGridViewRow();

            // Add enabled
            DataGridViewCheckBoxCell enabledCell = new DataGridViewCheckBoxCell();
            enabledCell.Value = enabled;
            listenerRow.Cells.Add(enabledCell);

            // Add className
            DataGridViewTextBoxCell classNameCell = new DataGridViewTextBoxCell();
            classNameCell.Value = className;
            listenerRow.Cells.Add(classNameCell);

            return listenerRow;
        }


        public bool Dirty
        {
            get 
            {
                return _dirty;
            }
        }

        private void WriteChanges()
        {
            foreach (Listener item in _configFile.AuditingConfiguration.Listeners)
            {
                item.Enabled = IsEnabled(item.ClassName);
            }
            _configFile.WriteConfigToFile();
        }

        private bool IsEnabled(string className)
        {
            foreach (DataGridViewRow dgvr in dataGridViewListeners.Rows)
            {
                if ((string)dgvr.Cells["ClassNameCol"].Value  == className)
                {
                    return (bool)dgvr.Cells["EnabledCol"].Value;
                }
            }

            throw new Exception("Cannot find the correct listener name");
        }

        private void buttonExecuteResetListenerFiles_Click(object sender, EventArgs e)
        {
            RefreshAuditFiles();
        }

        private void RefreshAuditFiles()
        {
            try
            {
                ServiceController myService = new ServiceController(_epmAuditServiceName);
                myService.ExecuteCommand((int)SimpleServiceCustomCommand.StartNewFile);
                MessageBox.Show("Refresh Audit Files sent to service", "EPM Auditing", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch
            {
                MessageBox.Show("Refresh Audit Files failed", "EPM Auditing", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


    }
}
